package org.example.core;

import org.example.constant.constant;
import org.example.util.HttpUtil;
import org.example.util.LogUtil;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/*
    分块下载任务
 */
public class DownloaderTask implements Callable<Boolean> {

    private String url;

    private long startPos;

    private long endPos;
    //标识当前是第几块
    private int part;

    private CountDownLatch countDownLatch;

    public DownloaderTask() {
    }

    public DownloaderTask(String url, long startPos, long endPos, int part,CountDownLatch countDownLatch) {
        this.url = url;
        this.startPos = startPos;
        this.endPos = endPos;
        this.part = part;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public Boolean call() throws Exception {

        String httpFileName = HttpUtil.getHttpFileName(url);

        //分块文件名
        httpFileName =  httpFileName + ".temp" + part;

        //存放路径
        httpFileName = constant.PATH + httpFileName;

        //获取分块下载链接
        HttpURLConnection httpURLConnection = HttpUtil.getHttpURLConnection(url,startPos,endPos);

        try (   InputStream input = httpURLConnection.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(input);
                RandomAccessFile raf = new RandomAccessFile(httpFileName,"rw");
                ){
            int len = -1;
            byte[] buffer = new byte[constant.BYTE_SIZE];
            while ((len = bis.read(buffer)) != -1){
                //一秒内下载的数据之和，通过原子类进行操作
                DownloaderInfoThread.downSize.add(len);
                raf.write(buffer,0,len);
            }
        }catch (FileNotFoundException e){
            LogUtil.error("()下载文件不存在！"  , httpFileName);
            return false;
        }catch (Exception e){
            LogUtil.error("()文件下载失败" ,  httpFileName);
            return false;
        }finally {
//            if (httpURLConnection != null){
//                httpURLConnection.disconnect();
//            }
            httpURLConnection.disconnect();

            countDownLatch.countDown();
        }

        return true;
    }
}
